<template>
  <view class="detail-page">
    <!-- 页面内容（包含轮播图） -->
    <view class="page-content">
      <!-- 轮播图 -->
      <view class="carousel-container" v-if="carouselImages.length > 0">
        <swiper class="carousel-swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500">
          <swiper-item v-for="(image, index) in carouselImages" :key="index">
            <image :src="image" mode="aspectFill" class="carousel-image"></image>
          </swiper-item>
        </swiper>
      </view>

      <!-- 商品信息卡片 -->
      <view class="product-card">
        <view class="product-info">
          <view class="product-header">
            <view class="product-name-container">
              <view class="product-name-line"></view>
              <view class="product-name">{{ productInfo.name || '利群（软阳光长嘴）' }}</view>
            </view>
            <view class="follow-btn" :class="{ followed: !!productInfo.is_followed }" @click="toggleFollow">
              <text class="follow-text">{{ productInfo.is_followed ? '已关注' : '关注' }}</text>
            </view>
          </view>
          <view class="product-badge">
            <text class="badge-text">今日</text>
          </view>
          <view class="price-grid">
            <view class="price-item">
              <text class="price-label">批发价</text>
              <text class="price-value">¥{{ formatPrice(productInfo.wholesale_price || '318') }}</text>
              <view class="price-change">
                <u-icon name="info-circle" color="#999999" size="12"></u-icon>
              </view>
            </view>
            <view class="price-item">
              <text class="price-label">零售价</text>
              <text class="price-value">¥{{ formatPrice(productInfo.retail_price || '360') }}</text>
              <view class="price-change">
                <u-icon name="info-circle" color="#999999" size="12"></u-icon>
              </view>
            </view>
            <view class="price-item">
              <text class="price-label">行情价</text>
              <text class="price-value">¥{{ formatPrice(productInfo.market_price || '314') }}</text>
              <view class="price-change">
                <u-icon name="info-circle" color="#999999" size="12"></u-icon>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 历史行情图表 -->
      <view class="chart-section">
        <view class="chart-header">
          <view class="section-title-container">
            <view class="section-title-line"></view>
            <text class="section-title">历史行情</text>
          </view>
          <view class="time-tabs">
            <view 
              class="time-tab" 
              :class="{ active: activeTab === item.value }"
              v-for="item in timeTabs" 
              :key="item.value"
              @click="switchTab(item.value)"
            >
              {{ item.label }}
            </view>
          </view>
        </view>
        <view class="chart-date-range">
          <text class="date-text">{{ chartDateRange.start }}至{{ chartDateRange.end }}</text>
        </view>
        <view class="chart-container">
          <qiun-data-charts 
            v-if="chartReady"
            type="area" 
            :chartData="chartData" 
            :opts="chartOpts"
            :ontap="true"
            :tooltipShow="true"
            :onmovetip="true"
            :ontouch="true"
            :inScrollView="true"
            :pageScrollTop="pageScrollTop"
            @getIndex="onChartIndex"
          />
          <view class="chart-end-label" v-if="trendChartData.length">
            <view class="end-date-badge">{{ getCurrentDate() }}</view>
            <text class="end-price">¥{{ getCurrentPrice() }}</text>
          </view>
          <view class="chart-hover-tip" v-if="hoverTip.visible">
            <text>{{ hoverTip.date }}  ¥{{ hoverTip.price }}</text>
          </view>
        </view>
      </view>
      
      <!-- 价格趋势数据表格 -->
      <view class="data-table-section">
        <view class="table-header">
          <text class="col-date">日期</text>
          <text class="col-price">当日价格</text>
          <text class="col-change">涨跌</text>
        </view>
        <view class="table-body">
          <view 
            class="table-row" 
            v-for="(item, index) in displayHistoryData" 
            :key="index"
          >
            <text class="col-date">{{ formatTableDate(item.date) }}</text>
            <text class="col-price">{{ formatPrice(item.price) }}</text>
            <text class="col-change" :class="item.change > 0 ? 'change-up' : (item.change < 0 ? 'change-down' : 'change-stable')">
              {{ formatChange(item.change) }}
            </text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 加载状态 -->
    <u-loading-page :loading="loading" loading-text="加载中..."></u-loading-page>
  </view>
</template>

<script>
/**
 * 商品详情页面
 * @author 王勇程 <laughskydragon@qq.com>
  */
 import { productApi, favoriteApi, priceApi } from '@/api'
 const { getProductDetail, getProductHistory } = productApi
 import { formatPrice, formatChange, formatDate, normalizeImageUrl } from '@/utils/common'

export default {
  data() {
    return {
      productId: '',
      productInfo: {},
      trendChartData: [],
      recentHistoryList: [],
      relatedProducts: [], // 相关商品数据
      loading: false,
      activeTab: '7d',
      timeTabs: [
        { label: '7天', value: '7d' },
        { label: '30天', value: '30d' },
        { label: '90天', value: '90d' },
        { label: '1年', value: '1y' },
        { label: '3年', value: '3y' }
      ],
      chartDateRange: {
        start: '2025-09-12',
        end: '2025-09-18'
      },
      carouselImages: [],
      chartData: null,
      chartReady: false,
      pageScrollTop: 0,
      hoverTip: { visible: false, date: '', price: '' },
      chartOpts: {
        legend: { show: false },
        dataLabel: false,
        color: ['#ee4133'],
        padding: [20, 40, 10, 26],
        xAxis: { disableGrid: true, boundaryGap: 'center', labelCount: 3 },
        yAxis: { splitNumber: 5, gridType: 'dash', format: val => '¥' + Math.round(val) },
        extra: { area: { gradient: true, opacity: 0.2, addLine: true, width: 3, type: 'curve' }, tooltip: { showBox: true } },
        enableScroll: false,
        ontap: true,
        tooltipShow: true
      }
    }
  },
  
  computed: {
    // 根据当前选择的时间段显示对应的历史数据
    displayHistoryData() {
      return this.recentHistoryList.slice(0, 10)
    }
  },
  
  onLoad(options) {
    if (options.id) {
      this.productId = options.id
      this.loadProductDetail()
    } else {
      // 如果没有传入ID，显示错误提示
      uni.showToast({
        title: '商品ID不能为空',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateBack()
      }, 1500)
    }
  },
  onPageScroll(e) {
    this.pageScrollTop = (e && typeof e.scrollTop === 'number') ? e.scrollTop : 0
  },
  
  methods: {
    normalizeImage(val) {
      return normalizeImageUrl(val)
    },

    
    /**
     * 显示更多操作
     */
    showMore() {
      const favoriteText = this.productInfo.is_followed ? '取消收藏' : '收藏'
      
      uni.showActionSheet({
        itemList: ['分享', favoriteText],
        success: (res) => {
          if (res.tapIndex === 0) {
            this.shareProduct()
          } else if (res.tapIndex === 1) {
            this.favoriteProduct()
          }
        }
      })
    },
    
    /**
     * 切换关注状态
     */
    toggleFollow() {
      this.favoriteProduct()
    },
    
    /**
     * 分享商品
     */
    shareProduct() {
      uni.showToast({
        title: '分享功能开发中',
        icon: 'none'
      })
    },
    
    /**
     * 收藏/取消收藏商品
     */
     async favoriteProduct() {
       try {
         const userInfo = uni.getStorageSync('user_info')
         const userToken = uni.getStorageSync('user_token')
         if (!userInfo || !userToken) {
           uni.showToast({ title: '请先登录', icon: 'none' })
           return
         }
         const isFollowed = this.productInfo.is_followed
         const result = await favoriteApi.toggleFavorite({
           user_token: userToken,
           product_id: this.productId
         })
         this.productInfo.is_followed = !isFollowed
         let msg = ''
         if (Array.isArray(result)) {
           msg = String(result[1] || result[0] || '')
         } else if (result && typeof result === 'object' && typeof result.is_followed !== 'undefined') {
           this.productInfo.is_followed = !!result.is_followed
         }
         uni.showToast({
           title: this.productInfo.is_followed ? (msg || '关注成功') : (msg || '已取消关注'),
           icon: 'success'
         })
       } catch (error) {
         if (error && (error.code === 1000001 || error.code === 1000002 || error.code === 1000005)) {
           uni.showToast({ title: '登录已过期，请重新登录', icon: 'none' })
         } else {
           uni.showToast({ title: error?.message || '操作失败，请重试', icon: 'none' })
         }
       }
     },
    
    /**
     * 切换时间段
     */
    switchTab(value) {
      this.activeTab = value
      this.loadHistoryData()
    },
    
    /**
     * 获取当前价格（用于图表显示）
     */
    getCurrentPrice() {
      if (this.trendChartData.length > 0) {
        const lastData = this.trendChartData[this.trendChartData.length - 1]
        return this.formatPrice(lastData.price)
      }
      return '347.0'
    },
    
    /**
     * 获取当前日期（用于图表显示）
     */
    getCurrentDate() {
      if (this.trendChartData.length > 0) {
        const lastData = this.trendChartData[this.trendChartData.length - 1]
        return this.formatTableDate(lastData.date)
      }
      return '2025-09-18'
    },
    

    
    /**
     * 更新图表日期范围
     */
  updateChartDateRange() {
    if (this.trendChartData.length > 0) {
        this.chartDateRange.start = this.trendChartData[0].date
        this.chartDateRange.end = this.trendChartData[this.trendChartData.length - 1].date
    }
  },

    // 加载商品详情（使用聚合接口）
    async loadProductDetail() {
      this.loading = true
      
      try {
        // 优先使用聚合接口 getDetailPage，包含商品详情、价格历史、关注状态等
        const res = await productApi.getDetailPage({
          product_id: this.productId
        })
        
        // 处理各种API响应格式
        let detailData = null
        
        if (res && res.code === 0) {
          // OneBase标准响应格式
          if (res.data) {
            detailData = res.data
          }
        } else if (res && typeof res === 'object' && !res.code) {
          // 直接返回数据对象
          detailData = res
        } else if (res && res.code && res.code !== 0) {
          // API返回错误，尝试使用基础接口
          console.warn('聚合接口失败，尝试基础接口:', res.msg)
          return await this.loadBasicProductDetail()
        }
        
        if (detailData) {
          // 处理聚合接口返回的数据
          const productData = detailData.product || detailData
          const priceHistory = detailData.price_history || {}
          const relatedProducts = detailData.related_products || []
          
          // 标准化商品信息数据
          this.productInfo = {
            id: productData.id || productData.product_id || this.productId,
            name: productData.name || productData.product_name || '未知商品',
            wholesale_price: parseFloat(productData.wholesale_price || productData.price || 0),
            retail_price: parseFloat(productData.retail_price || productData.guide_price || productData.price || 0),
            market_price: parseFloat(productData.current_price || productData.market_price || productData.price || 0),
            image: productData.image || productData.image_url || '/static/images/default-product.png',
            category: productData.category || '其他',
            spec: productData.spec || productData.specification || '',
            description: productData.description || '',
            update_time: productData.update_time || productData.update_time,
            change_amount: parseFloat(productData.change_amount || 0),
                change_rate: parseFloat(productData.change_rate || 0),
            price_trend: productData.price_trend || 'flat',
            is_followed: Boolean(detailData.is_followed || productData.is_followed || productData.is_favorite)
          }

          // 动态更改页面标题为商品名称
          uni.setNavigationBarTitle({
            title: this.productInfo.name || '商品详情'
          })

          // 轮播图（多图）
          const imagesArr = Array.isArray(productData.images) ? productData.images : []
          this.carouselImages = imagesArr.map(img => this.normalizeImage(img.path || img.url || img))
          
          const chartArr = Array.isArray(priceHistory.chart_data) ? priceHistory.chart_data : []
          this.trendChartData = chartArr.map(item => ({
            date: item.date,
            price: String(item.price || 0)
          }))
        if (this.trendChartData.length > 0) {
            this.trendChartData.sort((a, b) => new Date(a.date) - new Date(b.date))
            const tab = this.activeTab
            const daysMap = { '7d': 7, '30d': 30, '90d': 90, '1y': 365, '3y': 365 * 3 }
            const days = daysMap[tab] || 30
            this.normalizeTrendDataForPeriod(days)
            this.updateChartDateRange()
            this.updateChartData()
        }

          const listArr = priceHistory.list && Array.isArray(priceHistory.list.data) ? priceHistory.list.data : []
          if (listArr.length > 0) {
            const normalized = listArr.map(r => ({
              date: r.price_date,
              price: String(r.price || 0),
              change: parseFloat(r.change_amount || 0)
            }))
            this.recentHistoryList = normalized.sort((a, b) => new Date(b.date) - new Date(a.date))
          } else {
            this.recentHistoryList = []
          }
          if (this.recentHistoryList.length <= 1) {
            const basePrice = parseFloat((listArr[0] && listArr[0].price) || this.productInfo.market_price || 0)
            this.fillRecentDaysForTable(basePrice, 10)
          }
          
          // 存储相关商品数据（可用于后续扩展）
          this.relatedProducts = relatedProducts || []
          
          // 记录浏览历史（异步执行，不影响页面显示）
          this.recordViewHistory()
          
          
          
        } else {
          throw new Error('商品数据为空')
        }
        
      } catch (error) {
        console.error('加载商品详情失败:', error)
        
        // 根据错误类型显示不同的提示
        if (error.message.includes('登录') || error.message.includes('token')) {
          uni.showToast({
            title: '请先登录查看商品详情',
            icon: 'none'
          })
        } else {
          uni.showToast({
            title: '加载失败',
            icon: 'none'
          })
        }
      } finally {
        this.loading = false
      }
    },
    
    // 基础商品详情接口（备用）
    async loadBasicProductDetail() {
      try {
        const res = await productApi.getProductDetail({
          product_id: this.productId
        })
        
        // 处理各种API响应格式
        let productData = null
        
        if (res && res.code === 0) {
          // OneBase标准响应格式
          if (res.data) {
            productData = res.data
          }
        } else if (res && typeof res === 'object' && !res.code) {
          // 直接返回数据对象
          productData = res
        } else if (res && res.code && res.code !== 0) {
          // API返回错误
          const errorMsg = res.msg || '获取商品信息失败'
          
          // 检查是否是token相关错误
          if (res.code === 1000001 || res.code === 1000002 || res.code === 1000005) {
            uni.showToast({
              title: '登录已过期，请重新登录',
              icon: 'none'
            })
          } else {
            uni.showToast({
              title: errorMsg,
              icon: 'none'
            })
          }
          throw new Error(errorMsg)
        }
        
        if (productData) {
          // 标准化商品信息数据
          this.productInfo = {
            id: productData.id || productData.product_id || this.productId,
            name: productData.name || productData.product_name || '未知商品',
            wholesale_price: parseFloat(productData.wholesale_price || productData.price || 0),
            retail_price: parseFloat(productData.retail_price || productData.price || 0),
            market_price: parseFloat(productData.current_price || productData.market_price || productData.price || 0),
            image: this.normalizeImage(productData.image || productData.image_url) || '/static/images/default-product.png',
            category: productData.category || '其他',
            spec: productData.spec || productData.specification || '',
            description: productData.description || '',
            update_time: productData.update_time || productData.update_time,
            change_amount: parseFloat(productData.change_amount || 0),
                change_rate: parseFloat(productData.change_rate || 0),
            price_trend: productData.price_trend || 'flat',
            is_followed: Boolean(productData.is_followed || productData.is_favorite)
          }
          
          // 记录浏览历史（异步执行，不影响页面显示）
          this.recordViewHistory()
          
          // 单独加载历史数据
          this.loadHistoryData()
          
        } else {
          throw new Error('商品数据为空')
        }
        
      } catch (error) {
        console.error('加载基础商品详情失败:', error)
        throw error
      }
    },
    
    // 加载历史数据
    async loadHistoryData() {
      try {
        const tab = this.activeTab
        const daysMap = { '7d': 7, '30d': 30, '90d': 90, '1y': 365, '3y': 365 * 3 }
        const days = daysMap[tab] || 30
        const res = await priceApi.getPriceTrend({
          product_id: this.productId,
          period: `${days}d`
        })
        
        // 处理各种API响应格式
        let historyObj = null
        
        if (res && res.code === 0) {
          historyObj = { chart_data: res.data }
        } else if (Array.isArray(res)) {
          historyObj = { chart_data: res }
        } else if (res && res.code && res.code !== 0) {
          // API返回错误
          const errorMsg = res.msg || '获取历史数据失败'
          
          // 检查是否是token相关错误
          if (res.code === 1000001 || res.code === 1000002 || res.code === 1000005) {
            console.warn('Token错误，使用模拟历史数据')
      } else {
            console.warn('API错误:', errorMsg)
          }
          throw new Error(errorMsg)
        }
        
        if (historyObj && Array.isArray(historyObj.chart_data)) {
          this.trendChartData = historyObj.chart_data.map(item => ({
            date: item.date,
            price: String(item.price || 0)
          }))
          this.trendChartData.sort((a, b) => new Date(a.date) - new Date(b.date))
          this.normalizeTrendDataForPeriod(days)
          this.updateChartDateRange()
          
        } else {
          throw new Error('历史数据为空')
        }
        
        this.updateChartData()
        
      } catch (error) {
        console.error('加载历史数据失败:', error)
        uni.showToast({
          title: '历史数据加载失败',
          icon: 'none'
        })
      }
    },
    
    updateChartData() {
      if (this.trendChartData.length === 0) { this.chartReady = false; return }
      // 7天显示使用短日期格式（MM-DD），其他使用完整日期格式（YYYY-MM-DD）
      const formatFunc = this.activeTab === '7d' ? this.formatDate : this.formatTableDate
      const categories = this.trendChartData.map(i => formatFunc(i.date))
      const data = this.trendChartData.map(i => parseFloat(i.price))
      const minRaw = Math.min(...data)
      const maxRaw = Math.max(...data)
      const rangeRaw = maxRaw - minRaw
      const range = Math.max(1, rangeRaw)
      const base = 10
      const buffer = Math.max(3, range * 0.10)
      let yMin = Math.floor((minRaw - buffer) / base) * base
      let yMax = Math.ceil((maxRaw + buffer) / base) * base
      if (yMin < 0) yMin = 0
      if (yMax <= yMin) yMax = yMin + base * 2
      const uniqueCount = new Set(data.map(v => Number.isFinite(v) ? v.toFixed(2) : String(v))).size
      const areaType = uniqueCount <= 2 ? 'straight' : 'curve'
      const newOpts = {
        ...this.chartOpts,
        yAxis: { ...this.chartOpts.yAxis, min: yMin, max: yMax, data: [{ min: yMin, max: yMax }] },
        extra: { ...this.chartOpts.extra, area: { ...this.chartOpts.extra.area, type: areaType }, tooltip: { ...this.chartOpts.extra.tooltip, showBox: true } }
      }
      const newData = { categories, series: [{ name: '价格', data }] }
      this.chartReady = false
      this.chartOpts = newOpts
      this.chartData = newData
      this.$nextTick(() => { this.chartReady = true })
    },
    onChartIndex(e) {
      const idx = typeof e?.currentIndex === 'number' ? e.currentIndex : -1
      if (idx >= 0 && idx < this.trendChartData.length) {
        const row = this.trendChartData[idx]
        this.hoverTip = { visible: true, date: this.formatTableDate(row.date), price: this.formatPrice(row.price) }
      } else {
        this.hoverTip = { visible: false, date: '', price: '' }
      }
    },
    normalizeTrendDataForPeriod(days) {
      if (!Array.isArray(this.trendChartData) || this.trendChartData.length === 0) return
      const sorted = this.trendChartData.slice().sort((a, b) => new Date(a.date) - new Date(b.date))
      const end = new Date(sorted[sorted.length - 1].date)
      const start = new Date(end)
      start.setDate(end.getDate() - Math.max(1, days) + 1)
      const map = {}
      for (let i = 0; i < sorted.length; i++) {
        const ds = this.formatTableDate(sorted[i].date)
        const pv = parseFloat(sorted[i].price) || 0
        map[ds] = pv
      }
      const earliestPrice = parseFloat(sorted[0].price) || parseFloat(this.productInfo.market_price) || 0
      let current = earliestPrice
      const filled = []
      const indexMap = {}
      const realDates = new Set(Object.keys(map))
      const d = new Date(start)
      while (d <= end) {
        const y = d.getFullYear()
        const m = String(d.getMonth() + 1).padStart(2, '0')
        const day = String(d.getDate()).padStart(2, '0')
        const ds = `${y}-${m}-${day}`
        if (Object.prototype.hasOwnProperty.call(map, ds)) {
          current = map[ds]
        }
        filled.push({ date: ds, price: String(current) })
        indexMap[ds] = filled.length - 1
        d.setDate(d.getDate() + 1)
      }
      let limit = days <= 90 ? days : (days <= 365 ? 180 : 240)
      if (filled.length > limit) {
        const keep = new Set()
        keep.add(0)
        keep.add(filled.length - 1)
        for (const ds of realDates) {
          const idx = indexMap[ds]
          if (typeof idx === 'number') keep.add(idx)
        }
        const step = Math.max(1, Math.ceil(filled.length / limit))
        for (let i = 0; i < filled.length; i += step) keep.add(i)
        const keptIdx = Array.from(keep).sort((a, b) => a - b)
        const reduced = []
        for (let i = 0; i < keptIdx.length; i++) {
          const row = filled[keptIdx[i]]
          reduced.push({ date: row.date, price: row.price })
        }
        this.trendChartData = reduced
      } else {
        this.trendChartData = filled
      }
    },
    
    // 格式化价格
    formatPrice(price) {
      const num = parseFloat(price) || 0
      return num.toFixed(1)
    },
    
    // 格式化涨跌值
    formatChange(change) {
      const num = parseFloat(change) || 0
      if (num === 0) return '0.0'
      return num > 0 ? `+${num.toFixed(1)}` : num.toFixed(1)
    },
    
    // 格式化涨跌幅
    formatPercent(percent) {
      const num = parseFloat(percent) || 0
      return num > 0 ? `+${num.toFixed(2)}%` : `${num.toFixed(2)}%`
    },
    
    // 格式化表格日期
    formatTableDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    
    // 格式化图表日期范围显示
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      return `${month}-${day}`
    },
    
    // 记录浏览历史
    async recordViewHistory() {
      return
    },

    // 获取价格变化样式类
    getChangeClass(change) {
      const changeValue = parseFloat(change)
      if (changeValue > 0) return 'change-up'
      if (changeValue < 0) return 'change-down'
      return 'change-flat'
    },
    
    // 自动补全表格最近N天数据（用于list不足时）
    fillRecentDaysForTable(basePrice, days = 10) {
      const priceVal = parseFloat(basePrice || 0)
      if (!priceVal || priceVal <= 0) return
      const filled = []
      for (let i = 0; i < days; i++) {
        const d = new Date()
        d.setDate(d.getDate() - i)
        const y = d.getFullYear()
        const m = String(d.getMonth() + 1).padStart(2, '0')
        const day = String(d.getDate()).padStart(2, '0')
        filled.push({ date: `${y}-${m}-${day}`, price: String(priceVal), change: 0 })
      }
      this.recentHistoryList = filled
    }
  }
}
</script>

<style scoped>
.detail-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 轮播图样式 */
.carousel-container {
  width: 100%;
  height: 500rpx;
}

.carousel-swiper {
  width: 100%;
  height: 100%;
}

.carousel-image {
  width: 100%;
  height: 100%;
}

.page-content {
  height: calc(100vh - 44px - 500rpx);
  padding-bottom: 20rpx;
}

/* 商品信息卡片 */
.product-card {
  background-color: #ffffff;
  margin: 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
  display: flex;
  align-items: flex-start;
  gap: 24rpx;
}

.product-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  overflow: hidden;
  background-color: #f5f5f5;
  flex-shrink: 0;
}

.product-image image {
  width: 100%;
  height: 100%;
}

.product-info {
  flex: 1;
}

.product-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12rpx;
}

.product-name-container {
  display: flex;
  align-items: center;
  flex: 1;
}

.product-name-line {
  width: 6rpx;
  height: 32rpx;
  background-color: #ea4148;
  margin-right: 16rpx;
  border-radius: 3rpx;
}

.product-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
  line-height: 1.4;
  flex: 1;
}

.follow-btn {
  padding: 12rpx 24rpx;
  background: linear-gradient(135deg, #ff767a 0%, #ea4148 100%);
  border-radius: 20rpx;
  margin-left: 16rpx;
}

.follow-text {
  color: #ffffff;
  font-size: 24rpx;
  font-weight: 500;
}

.more-btn {
  padding: 8rpx;
  margin-left: 16rpx;
}

/* 商品信息卡片样式 */
.product-badge {
  display: inline-block;
  background-color: #ea4148;
  color: #ffffff;
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.badge-text {
  font-weight: 500;
}

.price-grid {
  display: flex;
  gap: 24rpx;
  margin-top: 20rpx;
}

.price-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.price-label {
  font-size: 24rpx;
  color: #999999;
  margin-bottom: 8rpx;
}

.price-value {
  font-size: 28rpx;
  font-weight: 500;
  color: #ea4148;
  margin-bottom: 4rpx;
}

.price-change {
  position: absolute;
  top: -4rpx;
  right: -4rpx;
}

.change-up {
  color: #ea4148;
}

.change-down {
  color: #2ed573;
}

.change-flat {
  color: #999999;
}

/* 图表部分 */
.chart-section {
  background-color: #ffffff;
  margin: 0 20rpx 20rpx;
  border-radius: 16rpx;
  padding: 30rpx;
}

.chart-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30rpx;
}

.section-title-container {
  display: flex;
  align-items: center;
}

.section-title-line {
  width: 6rpx;
  height: 32rpx;
  background-color: #ea4148;
  margin-right: 16rpx;
  border-radius: 3rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333333;
}

.time-tabs {
  display: flex;
  gap: 20rpx;
}

.time-tab {
  padding: 8rpx 16rpx;
  font-size: 24rpx;
  color: #999999;
  border-radius: 20rpx;
  background-color: #f5f5f5;
  transition: all 0.3s;
  cursor: pointer;
}

.time-tab.active {
  background-color: #ea4148;
  color: #ffffff;
}

/* 图表容器优化 */
.chart-container {
  position: relative;
  height: 400rpx;
  background-color: #fafafa;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
}

.chart-canvas {
  width: 100%;
  height: 100%;
  border-radius: 12rpx;
}

.chart-overlay {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  background-color: rgba(255, 255, 255, 0.9);
  padding: 12rpx 16rpx;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.chart-hover-tip {
  position: absolute;
  bottom: 12rpx;
  left: 12rpx;
  background-color: rgba(255, 255, 255, 0.95);
  padding: 8rpx 12rpx;
  border-radius: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  border: 1rpx solid #f0f0f0;
  pointer-events: none;
}

.price-point {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.point-price {
  font-size: 28rpx;
  font-weight: 500;
  color: #ea4148;
  margin-bottom: 4rpx;
}

.point-date {
  font-size: 20rpx;
  color: #999999;
}

/* 图表日期范围样式优化 */
.chart-date-range {
  text-align: center;
  padding: 0 20rpx;
}

.date-text {
  font-size: 24rpx;
  color: #999999;
}

/* 数据表格样式优化 */
.data-table-section {
  background-color: #ffffff;
  margin: 0 20rpx 20rpx;
  border-radius: 16rpx;
  overflow: hidden;
}

.table-header {
  display: flex;
  align-items: center;
  padding: 24rpx 30rpx;
  background-color: #f3f3f3;
  border-bottom: 2rpx solid #f0f0f0;
  font-weight: 500;
  color: #333333;
  font-size: 28rpx;
}

.table-body {
  max-height: 600rpx;
  overflow-y: auto;
  padding: 0 30rpx;
}

.table-row {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.table-row:last-child {
  border-bottom: none;
}

.col-date {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
}

.col-price {
  flex: 1;
  font-size: 28rpx;
  text-align: center;
  color: #333333;
  font-weight: 500;
}

.col-change {
  flex: 1;
  font-size: 28rpx;
  text-align: right;
  font-weight: 500;
}

.col-change.change-up {
  color: #ea4148;
}

.col-change.change-down {
  color: #29af5a;
}

.col-change.change-flat {
  color: #999999;
}

/* 响应式优化 */
@media (max-width: 750rpx) {
  .price-grid {
    gap: 16rpx;
  }
  
  .price-value {
    font-size: 26rpx;
  }
  
  .time-tabs {
    gap: 12rpx;
  }
  
  .time-tab {
    padding: 6rpx 12rpx;
    font-size: 22rpx;
  }
}

.chart-end-label {
  position: absolute;
  top: 12rpx;
  right: 12rpx;
  display: flex;
  align-items: center;
  gap: 12rpx;
  pointer-events: none;
}

.end-date-badge {
  background-color: #ee4133;
  color: #ffffff;
  font-size: 22rpx;
  padding: 6rpx 12rpx;
  border-radius: 8rpx;
}

.end-price {
  color: #ee4133;
  font-size: 26rpx;
  font-weight: 500;
}
</style>
